<template>
  <view class="search-container">
    <!-- 搜索头部 -->
    <view class="search-header">
      <view class="search-bar">
        <!-- <view class="back-btn" @tap="goBack">
          <uni-icons type="left" size="20" color="#2D3748"></uni-icons>
        </view> -->
        <view class="search-input-wrapper">
          <view class="search-icon">
            <uni-icons type="search" size="18" color="#667eea"></uni-icons>
          </view>
          <input 
            class="search-input"
            type="text"
            placeholder="搜索农药、化肥、种子..."
            v-model="searchKeyword"
            @input="onSearchInput"
            @confirm="handleSearch"
            focus
          />
          <view v-if="searchKeyword" class="clear-btn" @tap="clearSearch">
            <uni-icons type="closeempty" size="16" color="#999"></uni-icons>
          </view>
        </view>
        <view class="search-action" @tap="handleSearch">
          <text>搜索</text>
        </view>
      </view>
      
      <!-- 热门搜索标签 -->
      <view v-if="!searchKeyword && !isSearching" class="hot-tags">
        <scroll-view scroll-x="true" class="hot-tags-scroll">
          <view class="hot-tags-list">
            <view 
              class="hot-tag"
              v-for="(tag, index) in hotTags"
              :key="index"
              @tap="searchByTag(tag)"
            >
              <uni-icons v-if="index < 3" type="fire" size="14" color="#FF6B6B"></uni-icons>
              <text>{{ tag }}</text>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 搜索内容区域 -->
    <view class="search-content">
      <!-- 搜索历史 -->
      <view v-if="!searchKeyword && !isSearching && searchHistory.length > 0" class="history-section">
        <view class="section-header">
          <view class="section-title">
            <uni-icons type="clock" size="18" color="#718096"></uni-icons>
            <text>搜索历史</text>
          </view>
          <view class="clear-history" @tap="clearHistory">
            <uni-icons type="trash" size="16" color="#999"></uni-icons>
          </view>
        </view>
        
        <view class="history-list">
          <view 
            class="history-item"
            v-for="(item, index) in searchHistory"
            :key="index"
            @tap="searchByHistory(item)"
          >
            <text class="history-text">{{ item }}</text>
            <view class="remove-history" @tap.stop="removeHistory(index)">
              <uni-icons type="closeempty" size="12" color="#999"></uni-icons>
            </view>
          </view>
        </view>
      </view>

      <!-- 搜索建议 -->
      <view v-if="searchKeyword && !isSearching && searchSuggestions.length > 0" class="suggestions-section">
        <view class="suggestions-list">
          <view 
            class="suggestion-item"
            v-for="(item, index) in searchSuggestions"
            :key="index"
            @tap="selectSuggestion(item)"
          >
            <view class="suggestion-icon">
              <uni-icons type="search" size="16" color="#999"></uni-icons>
            </view>
            <text class="suggestion-text">{{ item }}</text>
            <view class="suggestion-arrow">
              <uni-icons type="right" size="12" color="#E2E8F0"></uni-icons>
            </view>
          </view>
        </view>
      </view>

      <!-- 搜索结果 -->
      <view v-if="isSearching" class="results-section">
        <!-- 结果筛选 -->
        <view class="filter-bar">
          <scroll-view scroll-x="true" class="filter-scroll">
            <view class="filter-list">
              <view 
                class="filter-item"
                :class="{ 'active': currentFilter === 'all' }"
                @tap="changeFilter('all')"
              >
                <text>全部</text>
              </view>
              <view 
                class="filter-item"
                :class="{ 'active': currentFilter === 'price' }"
                @tap="changeFilter('price')"
              >
                <text>价格</text>
                <uni-icons type="arrowdown" size="12" color="#999"></uni-icons>
              </view>
              <view 
                class="filter-item"
                :class="{ 'active': currentFilter === 'sales' }"
                @tap="changeFilter('sales')"
              >
                <text>销量</text>
              </view>
              <view 
                class="filter-item"
                :class="{ 'active': currentFilter === 'rating' }"
                @tap="changeFilter('rating')"
              >
                <text>评价</text>
              </view>
            </view>
          </scroll-view>
        </view>

        <!-- 结果列表 -->
        <view v-if="searchResults.length > 0" class="results-list">
          <view 
            class="result-item"
            v-for="(item, index) in searchResults"
            :key="index"
            @tap="goToDetail(item)"
          >
            <view class="result-image-wrapper">
              <image :src="item.image" mode="aspectFill" class="result-image"></image>
              <view v-if="item.badge" class="result-badge">
                <text>{{ item.badge }}</text>
              </view>
            </view>
            
            <view class="result-info">
              <text class="result-name" v-html="highlightKeyword(item.name)"></text>
              <view class="result-specs">
                <text class="spec-text">{{ item.spec }}</text>
                <view class="rating">
                  <uni-icons type="star-filled" size="12" color="#FFD93D"></uni-icons>
                  <text class="rating-text">{{ item.rating }}</text>
                </view>
              </view>
              <view class="result-tags">
                <text v-if="item.freeShipping" class="tag free-shipping">包邮</text>
                <text v-if="item.authentic" class="tag authentic">正品</text>
                <text v-if="item.discount" class="tag discount">{{ item.discount }}折</text>
              </view>
              <view class="result-price">
                <text class="current-price">¥{{ parseFloat(item.price || 0).toFixed(2) }}</text>
                <text v-if="item.originalPrice" class="original-price">¥{{ parseFloat(item.originalPrice || 0).toFixed(2) }}</text>
                <text class="sales-count">{{ item.sales }}人付款</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 无搜索结果 -->
        <view v-else class="no-results">
          <view class="no-results-icon">
            <uni-icons type="search" size="60" color="#E2E8F0"></uni-icons>
          </view>
          <text class="no-results-title">没有找到相关商品</text>
          <text class="no-results-desc">试试其他关键词或浏览推荐商品</text>
          
          <!-- 推荐商品 -->
          <view class="recommend-section">
            <text class="recommend-title">为您推荐</text>
            <view class="recommend-grid">
              <view 
                class="recommend-item"
                v-for="(item, index) in recommendProducts"
                :key="index"
                @tap="goToDetail(item)"
              >
                <image :src="item.image" mode="aspectFill" class="recommend-image"></image>
                <text class="recommend-name">{{ item.name }}</text>
                <text class="recommend-price">¥{{ parseFloat(item.price || 0).toFixed(2) }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 默认状态 -->
      <view v-if="!searchKeyword && !isSearching && searchHistory.length === 0" class="empty-state">
        <view class="empty-icon">
          <uni-icons type="search" size="80" color="#E2E8F0"></uni-icons>
        </view>
        <text class="empty-title">发现好商品</text>
        <text class="empty-desc">搜索你需要的农药、化肥、种子</text>
      </view>
    </view>

    <!-- 底部安全区域 -->
    <view class="bottom-safe"></view>
  </view>
</template>

<script>
import { getGoodsList } from '@/api/goods'

export default {
  data() {
    return {
      searchKeyword: '',
      isSearching: false,
      currentFilter: 'all',
      searchHistory: [],
      searchSuggestions: [],
      searchResults: [],
      hotTags: [
        '杀虫剂',
        '除草剂', 
        '杀菌剂',
        '复合肥',
        '有机肥',
        '种子',
        '农具',
        '植物营养液'
      ],
      recommendProducts: [
        {
          id: 1,
          name: '百泰 60%唑醚代森联',
          price: 99.00,
          image: 'http://gips0.baidu.com/it/u=1690853528,2506870245&fm=3028&app=3028&f=JPEG&fmt=auto?w=1024&h=1024'
        },
        {
          id: 2,
          name: '亩旺特 螺虫乙酯',
          price: 168.50,
          image: 'http://gips0.baidu.com/it/u=1690853528,2506870245&fm=3028&app=3028&f=JPEG&fmt=auto?w=1024&h=1024'
        }
      ]
    }
  },

  onLoad(options) {
    // 从其他页面传入的搜索关键词
    if (options.keyword) {
      this.searchKeyword = options.keyword
      this.handleSearch()
    }
    
    this.loadSearchHistory()
  },

  methods: {
    // 返回
    goBack() {
      uni.navigateBack()
    },

    // 搜索输入
    onSearchInput(e) {
      const keyword = e.detail.value
      this.searchKeyword = keyword
      
      if (keyword) {
        this.loadSuggestions(keyword)
      } else {
        this.searchSuggestions = []
        this.isSearching = false
      }
    },

    // 执行搜索
    handleSearch() {
      if (!this.searchKeyword.trim()) {
        return
      }

      this.isSearching = true
      this.searchSuggestions = []
      
      // 添加到搜索历史
      this.addToHistory(this.searchKeyword)
      
      // 模拟搜索
      setTimeout(() => {
        this.performSearch(this.searchKeyword)
      }, 500)
    },

    // 执行搜索请求
    performSearch(keyword) {
      // 模拟搜索结果
      const mockResults = [
        {
          id: 1,
          name: '百泰 60%唑醚代森联 水分散粒剂',
          spec: '500ml/瓶',
          price: 99.00,
          originalPrice: 120.00,
          rating: 4.8,
          sales: 1580,
          image: 'http://gips0.baidu.com/it/u=1690853528,2506870245&fm=3028&app=3028&f=JPEG&fmt=auto?w=1024&h=1024',
          badge: '热销',
          freeShipping: true,
          authentic: true,
          discount: 8.3
        },
        {
          id: 2,
          name: '亩旺特 22.4%螺虫乙酯 悬浮剂',
          spec: '200ml/瓶',
          price: 168.50,
          originalPrice: 180.00,
          rating: 4.9,
          sales: 890,
          image: 'http://gips0.baidu.com/it/u=1690853528,2506870245&fm=3028&app=3028&f=JPEG&fmt=auto?w=1024&h=1024',
          badge: '新品',
          freeShipping: true,
          authentic: true
        }
      ]

      // 过滤包含关键词的结果
      this.searchResults = mockResults.filter(item => 
        item.name.toLowerCase().includes(keyword.toLowerCase())
      )
    },

    // 高亮关键词
    highlightKeyword(text) {
      if (!this.searchKeyword) return text
      
      const regex = new RegExp(`(${this.searchKeyword})`, 'gi')
      return text.replace(regex, '<span style="color: #667eea; font-weight: bold;">$1</span>')
    },

    // 标签搜索
    searchByTag(tag) {
      this.searchKeyword = tag
      this.handleSearch()
    },

    // 历史搜索
    searchByHistory(keyword) {
      this.searchKeyword = keyword
      this.handleSearch()
    },

    // 选择搜索建议
    selectSuggestion(suggestion) {
      this.searchKeyword = suggestion
      this.handleSearch()
    },

    // 清除搜索
    clearSearch() {
      this.searchKeyword = ''
      this.searchSuggestions = []
      this.isSearching = false
    },

    // 切换筛选
    changeFilter(filter) {
      this.currentFilter = filter
      
      // 根据筛选条件重新排序结果
      this.sortResults(filter)
    },

    // 排序结果
    sortResults(filter) {
      switch (filter) {
        case 'price':
          this.searchResults.sort((a, b) => a.price - b.price)
          break
        case 'sales':
          this.searchResults.sort((a, b) => b.sales - a.sales)
          break
        case 'rating':
          this.searchResults.sort((a, b) => b.rating - a.rating)
          break
        default:
          // 恢复默认排序
          break
      }
    },

    // 加载搜索建议
    loadSuggestions(keyword) {
      // 模拟搜索建议
      const suggestions = [
        '百泰唑醚代森联',
        '百泰杀菌剂',
        '百草枯除草剂',
        '巴斯夫农药'
      ]
      
      this.searchSuggestions = suggestions.filter(item => 
        item.includes(keyword)
      ).slice(0, 5)
    },

    // 加载搜索历史
    loadSearchHistory() {
      const history = uni.getStorageSync('searchHistory') || []
      this.searchHistory = history.slice(0, 10) // 最多显示10条
    },

    // 添加到搜索历史
    addToHistory(keyword) {
      let history = uni.getStorageSync('searchHistory') || []
      
      // 移除重复项
      history = history.filter(item => item !== keyword)
      
      // 添加到开头
      history.unshift(keyword)
      
      // 限制数量
      history = history.slice(0, 10)
      
      this.searchHistory = history
      uni.setStorageSync('searchHistory', history)
    },

    // 删除搜索历史项
    removeHistory(index) {
      this.searchHistory.splice(index, 1)
      uni.setStorageSync('searchHistory', this.searchHistory)
    },

    // 清空搜索历史
    clearHistory() {
      uni.showModal({
        title: '提示',
        content: '确定要清空搜索历史吗？',
        success: (res) => {
          if (res.confirm) {
            this.searchHistory = []
            uni.removeStorageSync('searchHistory')
          }
        }
      })
    },

    // 跳转到商品详情
    goToDetail(item) {
      uni.navigateTo({
        url: `/pages/goods/detail?id=${item.id}`
      })
    }
  }
}
</script>

<style lang="scss">
.search-container {
  min-height: 100vh;
  background: #F8FAFC;
}

.search-header {
  background: #fff;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
}

.search-bar {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  gap: 20rpx;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: #F7FAFC;
}

.search-input-wrapper {
  flex: 1;
  display: flex;
  align-items: center;
  background: #F7FAFC;
  border-radius: 50rpx;
  padding: 0 24rpx;
  height: 70rpx;
}

.search-icon {
  margin-right: 12rpx;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #2D3748;
  background: transparent;
  border: none;
}

.search-input::placeholder {
  color: #A0AEC0;
}

.clear-btn {
  padding: 8rpx;
}

.search-action {
  padding: 20rpx 24rpx;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 35rpx;
  
  text {
    color: #fff;
    font-size: 26rpx;
    font-weight: 500;
  }
}

.hot-tags {
  padding: 20rpx 0 30rpx;
}

.hot-tags-scroll {
  white-space: nowrap;
}

.hot-tags-list {
  display: flex;
  padding: 0 30rpx;
  gap: 20rpx;
}

.hot-tag {
  display: flex;
  align-items: center;
  padding: 12rpx 20rpx;
  background: linear-gradient(135deg, #F7FAFC, #EDF2F7);
  border-radius: 20rpx;
  white-space: nowrap;
  transition: all 0.3s ease;
  
  text {
    font-size: 24rpx;
    color: #4A5568;
    margin-left: 8rpx;
  }
}

.hot-tag:active {
  transform: scale(0.95);
  background: #E2E8F0;
}

.search-content {
  padding: 20rpx 0;
}

.history-section {
  background: #fff;
  margin: 0 30rpx 20rpx;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

.section-title {
  display: flex;
  align-items: center;
  
  text {
    font-size: 28rpx;
    color: #2D3748;
    font-weight: 500;
    margin-left: 12rpx;
  }
}

.clear-history {
  padding: 8rpx;
}

.history-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.history-item {
  display: flex;
  align-items: center;
  padding: 12rpx 20rpx;
  background: #F7FAFC;
  border-radius: 30rpx;
  transition: background-color 0.2s ease;
}

.history-item:active {
  background: #E2E8F0;
}

.history-text {
  font-size: 24rpx;
  color: #4A5568;
  margin-right: 8rpx;
}

.remove-history {
  padding: 4rpx;
}

.suggestions-section {
  background: #fff;
  margin: 0 30rpx;
  border-radius: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
  overflow: hidden;
}

.suggestions-list {
  padding: 0;
}

.suggestion-item {
  display: flex;
  align-items: center;
  padding: 24rpx 30rpx;
  border-bottom: 1rpx solid #F7FAFC;
  transition: background-color 0.2s ease;
}

.suggestion-item:last-child {
  border-bottom: none;
}

.suggestion-item:active {
  background: #F7FAFC;
}

.suggestion-icon {
  margin-right: 20rpx;
}

.suggestion-text {
  flex: 1;
  font-size: 28rpx;
  color: #2D3748;
}

.suggestion-arrow {
  margin-left: 20rpx;
}

.results-section {
  margin-top: 20rpx;
}

.filter-bar {
  background: #fff;
  padding: 20rpx 0;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}

.filter-scroll {
  white-space: nowrap;
}

.filter-list {
  display: flex;
  padding: 0 30rpx;
  gap: 40rpx;
}

.filter-item {
  display: flex;
  align-items: center;
  padding: 16rpx 0;
  border-bottom: 3rpx solid transparent;
  transition: all 0.3s ease;
  white-space: nowrap;
  
  text {
    font-size: 26rpx;
    color: #718096;
    margin-right: 6rpx;
  }
}

.filter-item.active {
  border-bottom-color: #667eea;
  
  text {
    color: #667eea;
    font-weight: 500;
  }
}

.results-list {
  padding: 0 30rpx;
}

.result-item {
  display: flex;
  background: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  transition: transform 0.2s ease;
}

.result-item:active {
  transform: scale(0.98);
}

.result-image-wrapper {
  position: relative;
  margin-right: 24rpx;
}

.result-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
}

.result-badge {
  position: absolute;
  top: 8rpx;
  left: 8rpx;
  background: linear-gradient(135deg, #FF6B6B, #FF5252);
  color: #fff;
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
}

.result-info {
  flex: 1;
}

.result-name {
  font-size: 28rpx;
  color: #2D3748;
  font-weight: 500;
  line-height: 1.4;
  margin-bottom: 12rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  overflow: hidden;
}

.result-specs {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12rpx;
}

.spec-text {
  font-size: 24rpx;
  color: #718096;
}

.rating {
  display: flex;
  align-items: center;
  
  .rating-text {
    font-size: 22rpx;
    color: #FFD93D;
    margin-left: 4rpx;
  }
}

.result-tags {
  display: flex;
  gap: 8rpx;
  margin-bottom: 15rpx;
}

.tag {
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 6rpx;
  font-weight: 500;
}

.tag.free-shipping {
  background: #E8F5E8;
  color: #38A169;
}

.tag.authentic {
  background: #EBF8FF;
  color: #3182CE;
}

.tag.discount {
  background: #FFF5F5;
  color: #E53E3E;
}

.result-price {
  display: flex;
  align-items: baseline;
  justify-content: space-between;
}

.current-price {
  font-size: 32rpx;
  color: #E53E3E;
  font-weight: bold;
}

.original-price {
  font-size: 24rpx;
  color: #A0AEC0;
  text-decoration: line-through;
  margin-left: 8rpx;
}

.sales-count {
  font-size: 22rpx;
  color: #718096;
}

.no-results {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx 40rpx;
}

.no-results-icon {
  margin-bottom: 30rpx;
}

.no-results-title {
  font-size: 32rpx;
  color: #4A5568;
  font-weight: 500;
  margin-bottom: 12rpx;
}

.no-results-desc {
  font-size: 26rpx;
  color: #718096;
  margin-bottom: 50rpx;
}

.recommend-section {
  width: 100%;
}

.recommend-title {
  font-size: 28rpx;
  color: #2D3748;
  font-weight: 500;
  margin-bottom: 24rpx;
  display: block;
}

.recommend-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.recommend-item {
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
  transition: transform 0.2s ease;
}

.recommend-item:active {
  transform: scale(0.95);
}

.recommend-image {
  width: 100%;
  height: 200rpx;
  border-radius: 12rpx;
  margin-bottom: 12rpx;
}

.recommend-name {
  font-size: 24rpx;
  color: #2D3748;
  line-height: 1.3;
  margin-bottom: 8rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  overflow: hidden;
}

.recommend-price {
  font-size: 26rpx;
  color: #E53E3E;
  font-weight: bold;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 40rpx;
  min-height: 60vh;
}

.empty-icon {
  margin-bottom: 40rpx;
}

.empty-title {
  font-size: 32rpx;
  color: #4A5568;
  font-weight: 500;
  margin-bottom: 12rpx;
}

.empty-desc {
  font-size: 26rpx;
  color: #718096;
}

.bottom-safe {
  height: env(safe-area-inset-bottom);
  height: constant(safe-area-inset-bottom);
}
</style> 